package com.haoxuer.umall.rest.resource;

import com.haoxuer.discover.config.utils.ConverResourceUtils;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.data.page.Order;
import com.haoxuer.discover.data.page.Page;
import com.haoxuer.discover.data.page.Pageable;
import com.haoxuer.umall.api.apis.ProductApi;
import com.haoxuer.umall.api.domain.list.CategoryList;
import com.haoxuer.umall.api.domain.list.ProductList;
import com.haoxuer.umall.api.domain.page.ProductPage;
import com.haoxuer.umall.api.domain.request.PlatformRequest;
import com.haoxuer.umall.api.domain.request.ProductSearchRequest;
import com.haoxuer.umall.api.domain.simple.CategorySimple;
import com.haoxuer.umall.api.domain.simple.ProductSimple;
import com.haoxuer.umall.data.dao.ProductCategoryDao;
import com.haoxuer.umall.data.dao.ProductDao;
import com.haoxuer.umall.data.entity.Product;
import com.haoxuer.umall.data.entity.ProductCategory;
import com.haoxuer.umall.rest.conver.CategorySimpleConver;
import com.haoxuer.umall.rest.conver.PageableConver;
import com.haoxuer.umall.rest.conver.ProductSimpleConver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class ProductResource implements ProductApi {

    @Autowired
    private ProductCategoryDao categoryDao;

    @Autowired
    private ProductDao productDao;

    @Override
    public ProductList all(PlatformRequest request) {
        ProductList result = new ProductList();
        List<Order> orders = new ArrayList<>();
        orders.add(Order.asc("id"));
        List<Product> categories = productDao.list(0, 1000, null, orders);
        List<ProductSimple> cs = ConverResourceUtils.coverCollect(categories, new ProductSimpleConver());
        result.setList(cs);

        return result;
    }

    @Override
    public ProductPage search(ProductSearchRequest request) {
        ProductPage result = new ProductPage();

        Pageable pageable = new PageableConver().conver(request);
        pageable.getFilters().add(Filter.like("name", request.getName()));
        Page<Product> page = productDao.page(pageable);
        ConverResourceUtils.coverPage(result,page,new ProductSimpleConver());
        return result;
    }

    @Override
    public CategoryList allCategory(PlatformRequest request) {
        CategoryList result = new CategoryList();

        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.ge("levelInfo", 2));
        List<Order> orders = new ArrayList<>();
        orders.add(Order.asc("lft"));
        List<ProductCategory> categories = categoryDao.list(0, 1000, filters, orders);
        List<CategorySimple> cs = ConverResourceUtils.coverCollect(categories, new CategorySimpleConver());
        result.setList(cs);

        return result;
    }

}
